"""
server.py - 交通事件处理平台服务器

该文件包含与前端交互的API接口，处理用户请求并返回可视化结果。
"""

from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
import io
import matplotlib.pyplot as plt
from datetime import datetime
from typing import Dict, Any
from traffic_platform import EnhancedComprehensiveTrafficPlatform
from result_visualizer import ResultVisualizer
import os

# 确保数据库目录存在
os.makedirs("D:\\ALOT数据库", exist_ok=True)
app = Flask(__name__)
CORS(app, resources={
    r"/api/*": {
        "origins": "*",
        "methods": ["GET", "POST", "OPTIONS"],
        "allow_headers": ["Content-Type"]
    }
})  # 允许跨域请求

# 初始化平台和可视化器
platform = EnhancedComprehensiveTrafficPlatform()
visualizer = ResultVisualizer()

@app.route('/api/health', methods=['GET'])
def health_check():
    """健康检查端点"""
    return jsonify({"status": "healthy", "version": "1.0.0"})

@app.route('/api/process_event', methods=['POST'])
def process_event():
    """处理交通事件并返回结果"""
    try:
        # 获取请求数据
        data = request.get_json()

        # 验证数据
        if not data or 'device_reports' not in data:
            return jsonify({"error": "缺少必要参数", "status": "failed"}), 400

        # 处理媒体数据
        media_data = data.get('media_data', {})
        ext_data = data.get('ext_data', {})

        # 处理事件
        result = platform.process_events(data['device_reports'], media_data, ext_data)

        # 生成可视化结果
        if result.get("status") == "success":
            try:
                img_bytes = visualize_result_to_bytes(result)
                import base64
                img_base64 = base64.b64encode(img_bytes).decode('utf-8')
                result["visualization"] = img_base64
            except Exception as e:
                print(f"生成可视化失败: {str(e)}")
                result["visualization_error"] = str(e)

        return jsonify(result)

    except Exception as e:
        return jsonify({"error": f"处理事件时出错: {str(e)}", "status": "failed"}), 500

@app.route('/api/get_visualization', methods=['POST'])
def get_visualization():
    """获取可视化结果图片"""
    try:
        data = request.get_json()

        if not data or 'result' not in data:
            return jsonify({"error": "缺少结果数据", "status": "failed"}), 400

        # 生成可视化图片
        img_bytes = visualize_result_to_bytes(data['result'])

        # 返回图片数据
        return send_file(
            io.BytesIO(img_bytes),
            mimetype='image/png',
            as_attachment=True,
            download_name=f'traffic_event_{data["result"].get("event_id", "unknown")}.png'
        )

    except Exception as e:
        return jsonify({"error": f"生成可视化时出错: {str(e)}", "status": "failed"}), 500

@app.route('/api/test_cases', methods=['GET'])
def get_test_cases():
    """获取测试用例"""
    try:
        test_cases = [
            {
                "id": 1,
                "name": "学校区域严重事故",
                "description": "模拟学校区域发生的严重车辆碰撞事故",
                "device_reports": {
                    "cam-001": [
                        int(datetime.now().timestamp()),
                        [116.305, 39.905],
                        0.92,
                        "车辆碰撞",
                        0.9,
                        True
                    ],
                    "cam-002": [
                        int(datetime.now().timestamp()) + 1,
                        [116.306, 39.906],
                        0.88,
                        "车辆碰撞",
                        0.85,
                        True
                    ]
                },
                "media_data": {
                    "images": [],
                    "videos": []
                },
                "ext_data": {
                    "weather": "clear",
                    "traffic_flow": 0.8
                }
            },
            {
                "id": 2,
                "name": "普通区域中等事故",
                "description": "模拟普通区域发生的车辆剐蹭事故",
                "device_reports": {
                    "cam-003": [
                        int(datetime.now().timestamp()),
                        [116.4, 40.0],
                        0.65,
                        "车辆剐蹭",
                        0.5,
                        False
                    ]
                },
                "media_data": {
                    "images": [],
                    "videos": []
                },
                "ext_data": {
                    "weather": "rain",
                    "traffic_flow": 0.6
                }
            },
            {
                "id": 3,
                "name": "普通区域轻微事件",
                "description": "模拟普通区域发生的车辆急刹事件",
                "device_reports": {
                    "cam-004": [
                        int(datetime.now().timestamp()),
                        [116.41, 40.01],
                        0.45,
                        "车辆急刹",
                        0.3,
                        False
                    ]
                },
                "media_data": {
                    "images": [],
                    "videos": []
                },
                "ext_data": {
                    "weather": "clear",
                    "traffic_flow": 0.3
                }
            }
        ]

        return jsonify({
            "status": "success",
            "test_cases": test_cases,
            "timestamp": datetime.now().isoformat()
        })

    except Exception as e:
        return jsonify({
            "status": "failed",
            "error": f"获取测试用例失败: {str(e)}",
            "timestamp": datetime.now().isoformat()
        }), 500

def visualize_result_to_bytes(result: Dict[str, Any]) -> bytes:
    """将可视化结果转换为字节流"""
    fig = visualizer.visualize_result(result)
    if fig is None:
        raise ValueError("无法生成可视化结果")

    # 保存到字节流
    img_bytes = io.BytesIO()
    fig.savefig(img_bytes, format='png', dpi=150, bbox_inches='tight')
    plt.close(fig)  # 关闭图形释放内存
    img_bytes.seek(0)

    return img_bytes.getvalue()

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)